package com.zhou.mongo.dao.impl;

import com.zhou.mongo.dao.StudentDao;
import com.zhou.mongo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class StudentImpl implements StudentDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Student student) {
        mongoTemplate.save(student);

    }

    @Override
    public Student findUserByName(String name) {
        //精确
        //Query query=new Query(Criteria.where("name").is(name));
       //模糊
        Query query=new Query(Criteria.where("name").regex(name));
        return mongoTemplate.findOne(query,Student.class);
    }

    @Override
    public int update(Student student) {
        mongoTemplate.save(student);
        return  1;
    }

    @Override
    public void deleteById(Integer id) {
        Query query=new Query(Criteria.where("id").is(id));
        Student student=mongoTemplate.findOne(query,Student.class);
        mongoTemplate.remove(student);
    }

    @Override
    public List<Student> findByPage(Integer pageNo, Integer pageSize) {
        Query query=new Query();
       if (pageNo<1) pageNo=1;
        int bg=(pageNo-1)*pageSize;
       //分页
        query.skip(bg).limit(pageSize);
        //排序
        query.with(Sort.by(
                Sort.Order.asc("age"),
                Sort.Order.desc("id")
        ));
        List<Student> list=mongoTemplate.find(query,Student.class);
        return list;
    }

}
